from db_config import db
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from flask_login import UserMixin

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(2048))  # 增加哈希值存储长度
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    last_login = db.Column(db.DateTime)

    # 历史记录关联
    history_records = db.relationship('HistoryRecord', backref='user', lazy=True)

    # 历史记录关联
    history_records = db.relationship('HistoryRecord', backref='user', lazy=True)
    
    # 历史记录关联
    history_records = db.relationship('HistoryRecord', backref='user', lazy=True)
    
    # 历史记录关联
    history_records = db.relationship('HistoryRecord', backref='user', lazy=True)
    
    # 历史记录关联
    history_records = db.relationship('HistoryRecord', backref='user', lazy=True)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
        
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
        
    @staticmethod
    def get_by_username(username):
        return User.query.filter_by(username=username).first()

class HistoryRecord(db.Model):
    __tablename__ = 'history_records'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    image_path = db.Column(db.String(255), nullable=False)
    prediction_result = db.Column(db.JSON)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    @staticmethod
    def get_user_history(user_id):
        return HistoryRecord.query.filter_by(user_id=user_id).order_by(HistoryRecord.created_at.desc()).all()